package com.github.butid.data.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.List;

/**
 * @author wangjing.dc@qq.com
 * @since 2020/8/18
 */
@Slf4j
public class CmdMessageToXmlEncoder extends MessageToByteEncoder<CmdMessage> {

    // 报文举例：
    //            <root><DEVID>11000103</DEVID><TRNTYPE>COMD</TRNTYPE><TRNCODE>60014</TRNCODE>" +
    //                    "<PTIME>2020080714524</PTIME><TRNEJ>0038207725</TRNEJ><COMD_PARA>" +
    //                    "<PARA1>DirInfo</PARA1>" +
    //                    "<PARA2>DirInfo_11000103.txt</PARA2>" +
    //                    "<PARA3>c:\\</PARA3>" +
    //                    "<PARA4></PARA4>" +
    //                    "<PARA5></PARA5>" +
    //                    "<PARA6></PARA6>" +
    //                    "</COMD_PARA></root>");
    // 加密后数据举例：
    // "A5FB9F50B59E19B90F54A3B1A84D05A80FCE6568C40136E218A02B4CCA39593407AA2CBDB5431B8CF6C0C63D67F0A0CB32287F96F0EF5E6F40E79B41421DBA20D7153C288316AF7C3FA15C394A44D0298210270CB89A7A9CA0C245D87B5A43ADFAC17D124F35EE49F0084D55AA9367C7C28E5D33D66520C47D244BE66D873A5F695A7D8BC36259CD9C1FD5296379F92E7BDF48D8B40F93E8F8BE4C693F75063CBBE11C107C9CD4186B185595790989E9B36A01A13CA5D871EC1553DC4DF03A3B3E49B75A793EAFBBA90936EC19177ECB5B915FA6041AB7D4C96BA3C95CDE1B393B31C97A1B7B0FD4A545C21C9A2BF972BB503E94DF4090178FD5038421443C57989B4AA098C1B74DCDB9CD21B0FB3D596370618B3B6ABE27";
    @Override
    protected void encode(ChannelHandlerContext ctx, CmdMessage msg, ByteBuf out) {
        try {
            String xml = toXmlString(msg);
            out.writeBytes(ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(xml), Charset.forName("utf-8")));
        }catch (Exception e){
            ctx.fireExceptionCaught(e);
            ctx.close();
        }
    }

    /**
     * 对象转化为xml字符串
     * @param msg
     * @return
     */
    private String toXmlString(CmdMessage msg) {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("root");

        Header header = msg.getHeader();
        root.add(newElement("DEVID", header.getTermId()));
        root.add(newElement("TRNTYPE", header.getCmdType()));
        root.add(newElement("TRNCODE", header.getCmdCode()));
        root.add(newElement("PTIME", header.getDateImte()));
        root.add(newElement("TRNEJ", header.getServerSeq()));

        Element paramEle = DocumentHelper.createElement("COMD_PARA");
        root.add(paramEle);
        List<String> body = (List<String>) msg.getBody().get("COMD_PARA");
        for (int i = 0; i < 6; i++) {
            if (i < body.size()) {
                paramEle.add(newElement("PARA" + (i + 1), body.get(i)));
            } else {
                paramEle.add(newElement("PARA" + (i + 1), ""));
            }
        }

        return document.asXML();
    }

    /**
     * 快速船舰Element对象
     * @param name
     * @param value
     * @return
     */
    private Element newElement(String name, String value) {
        return DocumentHelper.createElement(name).addText(null == value? "" : value);
    }
}